﻿@{
    Layout = "~/Views/Shared/_FormWhite.cshtml";
    var operatorInfo = ViewData["OperatorInfo"] as OperatorInfo;
}
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment HostingEnvironment
@section header {
    <link href="@Url.Content("~/lib/summernote/0.8.15/summernote.min.css")" rel="stylesheet" type="text/css">
    <script src='@Url.Content("~/lib/summernote/0.8.15/summernote.js")' type="text/javascript"></script>
    <script src='@Url.Content("~/lib/summernote/0.8.15/lang/summernote-zh-CN.min.js")' type="text/javascript"></script>

    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/imageupload/1.0/css/imgup.min.css"))
    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/imageupload/1.0/js/imgup.min.js"))

    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/bootstrap.tagsinput/0.8.0/bootstrap-tagsinput.min.css"))
    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/bootstrap.tagsinput/0.8.0/bootstrap-tagsinput.min.js"))

    <!--引入 element-ui 的样式，-->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 必须先引入vue，后使用element-ui -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
    <!-- 引入element 的组件库-->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>

    <style>
        .custom-upload {
            display: inline-block;
        }
        .el-upload--picture-card {
            width: 148px;
            height: 148px;
            line-height: 148px;
        }
        .el-upload-list--picture-card .el-upload-list__item {
            width: 148px;
            height: 148px;
        }

        .el-upload__input {
            display:none;
        }

         .video-list {
          display: flex;
          margin-top: 10px;
      }
      .video-item {
          width: 300px;
           position: relative;
     }
       .video-item video {
          width: 100%;
          height: 180px;
          object-fit: cover;
          border-radius: 4px;
     }
       .video-delete {
           position: absolute;
         right: 5px;
          top: 5px;
          cursor: pointer;
       }

        input[type="file"] {
            display: none;
        }
    </style>
}

<div id="app" class="wrapper animated fadeInRight">
    <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="标题" required>
            <el-input v-model="form.title" :disabled="!isCreator"></el-input>
        </el-form-item>

        <el-form-item label="内容" required>
            <div id="content" class="summernote" :disabled="!isCreator"></div>
        </el-form-item>

        <el-form-item label="封面" required>
            <el-upload 
                :action="uploadUrl"
                list-type="picture-card"
                :hide-input="true"
                :multiple="false"
                :on-success="handleCoverImageSuccess"
                class="custom-upload"
                :show-file-list="false"
                :disabled="!isCreator"
                :on-remove="handleRemove">
                <img v-if="form.cover_image" :src="form.cover_image" style="width:100%" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>

        <el-form-item label="图片" required>
            <el-upload 
                :action="uploadUrl"
                list-type="picture-card"
                :hide-input="true"
                :multiple="true"
                :on-success="handleImagesSuccess"
                class="custom-upload"
                :file-list="fileList"
                :disabled="!isCreator"
                :on-remove="handleImagesRemove">
                <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>
        <el-form-item label="视频">
            <el-upload class="upload-demo"
                       :action="uploadVideoUrl"
                       :on-success="handleVideoSuccess"
                       :before-upload="beforeVideoUpload"
                       :show-file-list="false"
                       :disabled="!isCreator || videoList.length >= 1"
                       accept=".mp4">
                <el-button size="small" type="primary" 
                         :disabled="!isCreator || videoList.length >= 1">
                    {{ videoList.length >= 1 ? '已上传视频' : '点击上传视频' }}
                </el-button>
                <div slot="tip" class="el-upload__tip">只能上传mp4文件</div>
            </el-upload>
            <div class="video-list">
                <div v-if="videoList.length > 0" class="video-item">
                    <video :src="videoList[0].url" controls></video>
                    <el-button class="video-delete"
                               type="danger"
                               size="mini"
                               icon="el-icon-delete"
                               circle
                               :disabled="!isCreator"
                               v-on:click="handleVideoRemove(videoList[0])">
                    </el-button>
                </div>
            </div>
        </el-form-item> 
 
        <el-form-item label="状态" required>
            <el-radio-group v-model="form.state" :disabled="!canEditState">
                <el-radio :label="0">待审核</el-radio>
                <el-radio :label="1">通过</el-radio>
                <el-radio :label="2">拒绝</el-radio>
            </el-radio-group>
        </el-form-item>
    </el-form>
</div>

<script type="text/javascript">
    var id = ys.request("id");
    var currentUserId = '@(operatorInfo?.UserId)';
    var isAdmin = '@(operatorInfo?.IsSystem)' === '1';
    
    var vm = new Vue({
        el: '#app',
        data: {
            uploadUrl: '@GlobalContext.SystemConfig.ApiSite' + '/File/UploadFile?fileModule=@UploadFileType.Qixing.ParseToInt()',
            uploadVideoUrl: '@GlobalContext.SystemConfig.ApiSite' + '/File/UploadFile?fileModule=@UploadFileType.QixingVideo.ParseToInt()',
            fileList: [],
            videoList: [],
            form: {
                Id: id || '',
                title: '',
                content: '',
                cover_image: '',
                state: 1,
                knowledgePostMedia: [],
                user_id: ''
            }
        },
        computed: {
            isCreator() {
                console.log('currentUserId',currentUserId)
                return this.form.user_id !== `${currentUserId}`;
            },
            canEditState() {
                return isAdmin || 
                       (this.form.Id && this.form.user_id !== currentUserId);
            }
        },
        methods: {
            getFormData() {
                if (this.form.Id > 0) {
                    var that = this;
                    ys.ajax({
                        url: '@Url.Content("~/QixingManage/KnowledgePosts/GetFormJson")' + '?id=' + that.form.Id,
                        type: 'get',
                        success: function (obj) {
                            if (obj.Tag == 1) {
                                that.form = obj.Data;
                                // 处理图片列表
                                that.fileList = that.form.knowledgePostMedia
                                    .filter(item => item.media_type === 1)
                                    .map(item => ({
                                        name: item.media_url.split('/').pop(),
                                        url: item.media_url
                                    }));
                                // 处理视频列表
                                that.videoList = that.form.knowledgePostMedia
                                    .filter(item => item.media_type === 2)
                                    .map(item => ({
                                        name: item.media_url.split('/').pop(),
                                        url: item.media_url
                                    }));
                                $("#content").summernote('code', obj.Data.content);
                            }
                        }
                    });
                }
            },
              beforeVideoUpload(file) {
                const isVideo = file.type === 'video/mp4' || file.type === 'video/quicktime';
                const isLt100M = file.size / 1024 / 1024 < 100;
                
                if (!isVideo) {
                    this.$message.error('只能上传MP4/MOV格式的视频!');
                    return false;
                }
                if (!isLt100M) {
                    this.$message.error('视频大小不能超过100MB!');
                    return false;
                }
                return true;
            },
            handleVideoSuccess(response, file) {
                if (response.Tag == 1) {
                    // 如果已经有视频,先删除旧的
                    if (this.videoList.length > 0) {
                        this.videoList = [];
                        this.form.knowledgePostMedia = this.form.knowledgePostMedia.filter(
                            item => item.media_type !== 2
                        );
                    }
                
                    let videoUrl = '@GlobalContext.SystemConfig.ApiSite' + response.Data;
                    // 添加到显示列表
                    this.videoList.push({
                        name: file.name,
                        url: videoUrl
                    });
                    // 添加到表单数据
                    this.form.knowledgePostMedia.push({
                        media_url: videoUrl,
                        media_type: 2
                    });
                }
            },
            handleVideoRemove(file) {
                this.videoList = [];
                const mediaIndex = this.form.knowledgePostMedia.findIndex(item => 
                    item.media_url === file.url && item.media_type === 2
                );
                if (mediaIndex > -1) {
                    this.form.knowledgePostMedia.splice(mediaIndex, 1);
                }
            },
            handleCoverImageSuccess(response, file) {
                if (response.Tag == 1) {
                    this.form.cover_image = '@GlobalContext.SystemConfig.ApiSite' + response.Data;
                }
            },
            handleImagesSuccess(response, file) {
                if (response.Tag == 1) {
                    let imageUrl = '@GlobalContext.SystemConfig.ApiSite' + response.Data;
                    this.fileList.push({
                        name: file.name,
                        url: imageUrl
                    });
                    let image = {
                        media_url: imageUrl,
                        media_type: 1
                    };
                    this.form.knowledgePostMedia.push(image);
                }
            },
            handleImagesRemove(file) {
                const fileIndex = this.fileList.findIndex(item => item.url === file.url);
                if (fileIndex > -1) {
                    this.fileList.splice(fileIndex, 1);
                }
                const mediaIndex = this.form.knowledgePostMedia.findIndex(item => item.media_url === file.url);
                if (mediaIndex > -1) {
                    this.form.knowledgePostMedia.splice(mediaIndex, 1);
                }
            },
            handleRemove() {
                this.form.cover_image = '';
            },
            initializeSummernote() {
                $('#content').summernote({
                    height: '220px',
                    lang: 'zh-CN',
                    dialogsInBody: true,
                    toolbar: this.isCreator ? undefined : [],
                    disable: !this.isCreator,
                    callbacks: {
                        onImageUpload: function (files) {
                            uploadNewsImage(files[0], this);
                        }
                    }
                });
            }
        },
        mounted() {
            this.initializeSummernote();
            if (this.form.Id) {
                this.getFormData();
            }
        }
    });

    function uploadNewsImage(file, editor) {
        var formdata = new FormData();
        formdata.append("fileList", file);
        ys.ajaxUploadFile({
            url: '@GlobalContext.SystemConfig.ApiSite' + '/File/UploadFile?fileModule=@UploadFileType.Qixing.ParseToInt()',
            data: formdata,
            success: function (obj) {
                if (obj.Tag == 1) {
                    $(editor).summernote('insertImage', '@GlobalContext.SystemConfig.ApiSite' + obj.Data, '/');
                } else {
                    ys.msgError(obj.Message);
                }
            }
        });
    }

    function saveForm(index) {
        if (!vm.isCreator && !vm.canEditState) {
            ys.msgError("您没有权限执行此操作!");
            return;
        }

        if (!vm.form.title) {
            ys.msgError("请输入标题!");
            return;
        } 
        if (!$("#description").summernote('code')) {
            ys.msgError("请输入内容");
            return;
        }
        if (!vm.form.cover_image) {
            ys.msgError("请上传封面图片!");
            return;
        }
        if (!vm.form.knowledgePostMedia ||  vm.form.knowledgePostMedia.filter(t=>t.media_type ==1).length == 0) {
            ys.msgError("请上传图片!");
            return;
        }
        // if (!vm.form.knowledgePostMedia ||  vm.form.knowledgePostMedia.filter(t=>t.media_type == 2).length == 0) {
        //     ys.msgError("请上传视频!");
        //     return;
        // }
         
        var postData = vm.isCreator ? {
            Id: vm.form.Id,
            title: vm.form.title,
            content: $("#content").summernote('code'),
            cover_image: vm.form.cover_image,
            state: vm.form.state,
            knowledgePostMedia: vm.form.knowledgePostMedia
        } : {
            Id: vm.form.Id,
            state: vm.form.state
        };

        ys.ajax({
            url: '@Url.Content("~/QixingManage/KnowledgePosts/SaveFormJson")',
            type: 'post',
            data: postData,
            success: function (obj) {
                if (obj.Tag == 1) {
                    ys.msgSuccess(obj.Message);
                    parent.searchGrid();
                    parent.layer.close(index);
                } else {
                    ys.msgError(obj.Message);
                }
            }
        });
    }
</script>

